package com.samsung.spen.sshare.main;

import java.util.ArrayList;

import com.samsung.spen.sshare.R;
import com.samsung.spen.sshare.main.data.DataHelper;
import com.samsung.spen.sshare.main.data.HistoryColumns;
import com.samsung.spen.sshare.main.data.SshareDataService;
import com.samsung.spen.sshare.main.history.HistoryDetailActivity;
import com.samsung.spen.sshare.main.history.HistoryFragment;
import com.samsung.spen.sshare.main.sms.RequestSMSListFragment;
import com.samsung.spen.sshare.main.sms.SendSMSFragment;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.ContactsContract.PhoneLookup;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {
	TabHost mTabHost;
	ViewPager mViewPager;
	TabsAdapter mTabsAdapter;
	private String phoneFromDetail = "";
	public UpdateViewSMS updateViewSMS;
	public UpdateViewHistory updateViewHistory;


	
	// public SshareDataService mSshareDataService;
	// private ServiceConnection mServiceConnection = new ServiceConnection() {
	//
	// @Override
	// public void onServiceDisconnected(ComponentName name) {
	// mSshareDataService = null;
	// Toast.makeText(MainActivity.this, "service disconnected",
	// Toast.LENGTH_SHORT).show();
	// }
	//
	// @Override
	// public void onServiceConnected(ComponentName name, IBinder service) {
	// mSshareDataService = ((SshareDataService.SshareDataServiceBinder)
	// service)
	// .getService();
	// // use service here
	// Toast.makeText(MainActivity.this, "service connected",
	// Toast.LENGTH_SHORT).show();
	// Log.v(this.getClass().toString(), "service connected");
	// }
	// };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.main_sshare_activity_main);

		// this.bindService(new Intent(this, SshareDataService.class),
		// mServiceConnection, Context.BIND_AUTO_CREATE);

		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mTabsAdapter = new TabsAdapter(this, mTabHost, mViewPager);

		mTabsAdapter.addTab(
				mTabHost.newTabSpec("sendSMS").setIndicator("Send Request"),
				SendSMSFragment.class, null);
		mTabsAdapter
				.addTab(mTabHost.newTabSpec("requestList").setIndicator(
						"Request List"), RequestSMSListFragment.class, null);
		mTabsAdapter.addTab(
				mTabHost.newTabSpec("history").setIndicator("History"),
				HistoryFragment.class, null);
		Log.v(this.getClass().toString(), "oncreate mainActivity");
	}

	@Override
	protected void onRestart() {
		super.onRestart();
	}

	@Override
	protected void onActivityResult(int arg0, int resultCode, Intent data) {

		switch (resultCode) {
		case HistoryDetailActivity.RESULT_CODE_SEND_REQUEST:
			mTabHost.setCurrentTabByTag("sendSMS");
			phoneFromDetail = data.getStringExtra(HistoryColumns.PHONE_NUMBER);
		
			Log.d("BEBE", phoneFromDetail);
			if(updateViewSMS!=null){
				Log.d("BEBE", "not null");
				updateViewSMS.updateSMSFragment(phoneFromDetail);
			}


			break;
			
		case HistoryDetailActivity.RESULT_CODE_DELETE_DETAIL:
			if(updateViewSMS!=null){
			updateViewHistory.updateHistoryFragment();
			}
			break;
		default:
			break;
		}
		super.onActivityResult(arg0, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	public static class TabsAdapter extends FragmentPagerAdapter implements
			TabHost.OnTabChangeListener, ViewPager.OnPageChangeListener {

		private final Context mContext;
		private final TabHost mTabHost;
		private final ViewPager mViewPager;
		private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();

		static final class TabInfo {
			private final String tag;
			private final Class<?> clss;
			private final Bundle args;

			TabInfo(String _tag, Class<?> _class, Bundle _agrs) {
				tag = _tag;
				clss = _class;
				args = _agrs;
			}
		}

		static class DummyTabFactory implements TabHost.TabContentFactory {
			private final Context mContext;

			public DummyTabFactory(Context context) {
				mContext = context;
			}

			@Override
			public View createTabContent(String tag) {
				View v = new View(mContext);
				v.setMinimumHeight(0);
				v.setMinimumWidth(0);
				return v;
			}
		}

		public TabsAdapter(FragmentActivity activity, TabHost tabHost,
				ViewPager pager) {
			super(activity.getSupportFragmentManager());
			mContext = activity;
			mTabHost = tabHost;
			mViewPager = pager;
			mTabHost.setOnTabChangedListener(this);
			mViewPager.setAdapter(this);
			mViewPager.setOnPageChangeListener(this);
		}

		public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
			tabSpec.setContent(new DummyTabFactory(mContext));
			String tag = tabSpec.getTag();

			TabInfo info = new TabInfo(tag, clss, args);
			mTabs.add(info);
			mTabHost.addTab(tabSpec);
			notifyDataSetChanged();
		}

		@Override
		public void onTabChanged(String tabId) {
			int position = mTabHost.getCurrentTab();
			mViewPager.setCurrentItem(position);
		}

		@Override
		public Fragment getItem(int position) {
			TabInfo info = mTabs.get(position);
			return Fragment.instantiate(mContext, info.clss.getName(),
					info.args);
		}

		@Override
		public int getCount() {
			return mTabs.size();
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {

		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {

		}

		@Override
		public void onPageSelected(int position) {
			TabWidget widget = mTabHost.getTabWidget();
			int oldFocusability = widget.getDescendantFocusability();
			widget.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);
			mTabHost.setCurrentTab(position);
			widget.setDescendantFocusability(oldFocusability);
		}
	}
	
	public String getNameFromPhone(String phone){
		String name = "No contact";
		if (phone != null && !phone.equals("")) {
			Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
			Cursor cursor = this.getContentResolver().query(uri, new String[] { PhoneLookup.DISPLAY_NAME },
							null, null, null);
			if (cursor != null) {
				if (cursor.moveToFirst()) {
					name = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
				}
			}
		}
		return name;
	}
}
